package main

import (
	"LibraryManagementSys/internal/router"
	"LibraryManagementSys/pkg/config"
	"context"
	"flag"
	"go.uber.org/zap"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// 命令行参数, 用来表示程序启动的时候, 使用的配置文件类型
var env = flag.String("env", "dev", "配置文件类型")

// @title          Go 语言项目布局
// @version        1.0
// @description    演示 Go 语言项目布局
// @termsOfService https://swagger.io/terms/

// @contact.name  这里写联系人信息
// @contact.url   https://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url  https://www.apache.org/licenses/LICENSE-2.0.html

// @host     localhost:8080
// @BasePath /

// @securityDefinitions.apikey ApiKeyAuth
// @in                         header
// @name                       Authorization
// @description                Description for what is this security definition being used
func main() {
	flag.Parse()

	err := config.LoadConfig(*env)
	if err != nil {
		panic("加载配置文件出错:" + err.Error())
	}

	s := router.NewHttpServer()

	server := &http.Server{
		Addr:    ":" + config.Get().ServerConfig.Port,
		Handler: s,
	}

	// 开启一个协程监听网络请求
	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			zap.S().Errorf("listen: %s\n", err)
		}
	}()

	// Wait for interrupt signal to gracefully shut down the internal with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)

	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can"t be caught, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	<-quit
	zap.L().Info("Shutdown Server ...")

	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	if err := server.Shutdown(ctx); err != nil {
		zap.S().Errorf("internal shutdown: %s", err)
	}

	// catching ctx.Done(). timeout of 5 seconds.
	select {
	case <-ctx.Done():
		zap.L().Info("timeout of 5 seconds.")
	}

	zap.L().Info("Server exiting")

}
